/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.admin;

import com.hboxs.asl.Filter;
import com.hboxs.asl.entity.Area;
import com.hboxs.asl.entity.CourseTrade;
import com.hboxs.asl.entity.Question;
import com.hboxs.asl.qcloudLVB.entity.Live;
import com.hboxs.asl.qcloudLVB.service.LiveService;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.DateUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * Controller - 共用
 */
@Controller("adminCommonController")
@RequestMapping("/asl-admin/common")
public class CommonController implements ServletContextAware {

    @Value("${system.version}")
    private String systemVersion;
    @Value("${system.description}")
    private String systemDescription;
    @Value("${system.show_powered}")
    private Boolean systemShowPowered;
    @Resource(name = "areaServiceImpl")
    private AreaService areaService;
    @Resource(name = "captchaServiceImpl")
    private CaptchaService captchaService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "messageServiceImpl")
    private MessageService messageService;
    @Resource(name = "essayServiceImpl")
    private EssayService essayService;
    @Resource(name = "liveServiceImpl")
    private LiveService liveService;
    @Resource(name = "questionServiceImpl")
    private QuestionService questionService;
    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "courseTradeServiceImpl")
    private CourseTradeService courseTradeService;

    /**
     * servletContext
     */
    private ServletContext servletContext;

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * 主页
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String main() {
        return "/admin/common/main";
    }

    /**
     * 首页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap model) {

        model.addAttribute("systemName", "易经教育系统");
        model.addAttribute("systemVersion", systemVersion);
        model.addAttribute("systemDescription", systemDescription);
        model.addAttribute("systemShowPowered", systemShowPowered);
        model.addAttribute("javaVersion", System.getProperty("java.version"));
        model.addAttribute("javaHome", System.getProperty("java.home"));
        model.addAttribute("osName", System.getProperty("os.name"));
        model.addAttribute("osArch", System.getProperty("os.arch"));
        model.addAttribute("serverInfo", servletContext.getServerInfo());
        model.addAttribute("servletVersion", servletContext.getMajorVersion() + "." + servletContext.getMinorVersion());
        model.addAttribute("essayCount", essayService.count());
        model.addAttribute("liveCount", liveService.getHostLiveCounts(Live.Type.host));
        model.addAttribute("questionCount", questionService.count());
        model.addAttribute("answerCount", questionService.getQuestionCount(Question.AnswerStatus.yes));
        model.addAttribute("courseCount", courseService.count());
        model.addAttribute("courseOrderCount", courseTradeService.getCourseTradeCount(CourseTrade.PaymentStatus.paid));
        model.addAttribute("memberCount", memberService.count());
        model.addAttribute("unreadMessageCount", messageService.count(null, false));

        // 时间
        Filter startDateFilter = null;
        Filter endDateFilter = null;


        // 增加的会员数量
        Long memberCount = 0l;

        // 时间段内用户数量增加
        LinkedHashMap<Date, Long> memberCountsMap = new LinkedHashMap();
        Set<Long> menberCounts = new HashSet<>();
        for (int i = -7; i <= 0; i++) {
            Date d = DateUtils.getPastDate(i);

            startDateFilter = Filter.geDate("createDate", DateUtils.starOftDate(d));
            endDateFilter = Filter.leDate("createDate", DateUtils.endOfDate(d));
            memberCount = memberService.count(startDateFilter, endDateFilter);
            memberCountsMap.put(d, memberCount);
            menberCounts.add(memberCount);
        }
        model.addAttribute("memberCountsMap", memberCountsMap);
        // 坐标的最高值图表最高值的120%
        model.addAttribute("memberCountMax", Collections.max(menberCounts) * 1.5);

        return "/admin/common/index";
    }

    /**
     * 地区
     */
    @RequestMapping(value = "/area", method = RequestMethod.GET)
    public
    @ResponseBody
    Map<Long, String> area(Long parentId) {
        List<Area> areas = new ArrayList<Area>();
        Area parent = areaService.find(parentId);
        if (parent != null) {
            areas = new ArrayList<Area>(parent.getChildren());
        } else {
            areas = areaService.findRoots();
        }
        Map<Long, String> options = new HashMap<Long, String>();
        for (Area area : areas) {
            options.put(area.getId(), area.getName());
        }
        return options;
    }

    /**
     * 验证码
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(captchaId)) {
            captchaId = request.getSession().getId();
        }
        String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse().toString();
        String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse().toString();
        response.addHeader(pragma, value);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            BufferedImage bufferedImage = captchaService.buildImage(captchaId);
            ImageIO.write(bufferedImage, "jpg", servletOutputStream);
            servletOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(servletOutputStream);
        }
    }

    /**
     * 错误提示
     */
    @RequestMapping("/error")
    public String error() {
        return "/admin/common/error";
    }

    /**
     * 权限错误
     */
    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            response.addHeader("loginStatus", "unauthorized");
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        return "/admin/common/unauthorized";
    }

}